﻿using Bilibili.Common;
using Bilibili.Common.Api;
using Bilibili.Common.Database;
using Bilibili.WebClient.Common;
using PCLUntils.Objects;
using System;
using System.Collections.Generic;

namespace Bilibili.WebClient
{
    public sealed class Current
    {
        private static Current instance;
        public static Current Instance
        {
            get
            {
                instance ??= new Current();
                return instance;
            }
        }
        private Current() { }
        public string LocalID { get; private set; }
        private object HasInit { get; set; } = false;
        public Random Radom { get; private set; }
        public const string HOST = "http://www.bilibili.com/";
        public const string AOO_USER_AGENT = "Bilibili Freedoooooom/MarkII";
        public const string API_USER_AGENT = "Mozilla/5.0 BiliDroid/1.12.0 (bbcallen@gmail.com)"; 
        public const string STATISTICS = "%7B%22appId%22%3A1%2C%22platform%22%3A3%2C%22version%22%3A%227.27.0%22%2C%22abtest%22%3A%22%22%7D";
        public const string PLAY_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36";
        public const string MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Mobile Safari/537.36";
        public string GetBuvid()
        {
            var buvid = SettingHelper.Buvid;
            if (buvid.IsEmpty())
            {
                var mac = new List<string>();
                for (var i = 0; i < 6; i++)
                {
                    var min = Math.Min(0, 0xff);
                    var max = Math.Max(0, 0xff);
                    var num = Radom.Next(min, max).ToString("X");
                    mac.Add(num);
                }
                var md5 = string.Join(":", mac).ToMD5();
                var md5Arr = md5.ToCharArray();
                buvid = $"XY{md5Arr[2]}{md5Arr[12]}{md5Arr[22]}{md5}";
                SettingHelper.Buvid = buvid;
            }
            return buvid;
        }
        public IApiClient ApiClient { get; private set; }
        public void Init()
        {
            if (HasInit is bool value && value == false)
            {
                HasInit = true;
                Radom = new Random();
                ApiClient = SettingHelper.UseRest ? new RestClientEx() : new HttpClientEx();
                LocalID = Guid.NewGuid().ToString();
            }
        }
        public void Dispose()
        {
            try
            {
                ApiClient.Dispose();
            }
            catch { }
        }
    }
}